package com.example.demo.controller;

import com.example.demo.model.request.StudentQueryRequest;
import com.example.demo.model.response.FrontendResponse;
import com.example.demo.model.response.StudentResponse;
import com.example.demo.service.StudentService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpHeaders;

import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/api/student")
@RequiredArgsConstructor
public class StudentController {

    private final StudentService studentService;

    /**
     * 综合查询接口（同时返回相似学生和同目标院校学生）
     */
    @PostMapping("/query")
    public FrontendResponse queryStudents(@RequestBody StudentQueryRequest request) {
        try {
            StudentResponse data = studentService.queryStudentInfo(request);
            return new FrontendResponse(200, "查询成功", data);
        } catch (Exception e) {
            return new FrontendResponse(500, "查询失败：" + e.getMessage(), null);
        }
    }

    // 可拆分单独接口（按需）
    @PostMapping("/similar")
    public FrontendResponse getSimilar(@RequestBody StudentQueryRequest request) {
        try {
            return new FrontendResponse(200, "相似学生查询成功", studentService.getSimilarStudents(request));
        } catch (Exception e) {
            return new FrontendResponse(500, "查询失败：" + e.getMessage(), null);
        }
    }

    @PostMapping("/target-school")
    public FrontendResponse getByTargetSchool(@RequestBody StudentQueryRequest request) {
        try {
            return new FrontendResponse(200, "目标院校学生查询成功", studentService.getStudentsByTargetSchool(request));
        } catch (Exception e) {
            return new FrontendResponse(500, "查询失败：" + e.getMessage(), null);
        }
    }

    @PostMapping("/similar/export")
    public ResponseEntity<byte[]> exportSimilarStudents(@RequestBody StudentQueryRequest request) {
        try {
            // 1. 调用服务层生成Excel字节数组
            byte[] excelData = studentService.exportSimilarStudents(request);

            // 2. 设置响应头（文件名、类型等）
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment",
                    new String("相似学生信息.xlsx".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)); // 解决中文文件名乱码

            // 3. 返回文件流
            return new ResponseEntity<>(excelData, headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}